let query = require("../model/connect")
const jwt =require("jsonwebtoken");

// 用户相关路由
const express = require("express");
let router = express.Router();

//1.获取用户信息getusers
// 2.注册registry
// 3.登录并签发token  ：login

router.get("/getusers", async(req, res) => {
    let {id}=req.query;
    let str = `SELECT * FROM user WHERE id=${id}`;
    let result = await query(str)
    res.json({
        // info:"获取用户信息成功",
        status:1,
        result:result[0]
    })
})



router.post("/registry", async (req, res) => {
    // 注册
    // console.log(req.body);
    try {
        let { phone, password } = req.body;
        let reslut = await query(`INSERT INTO user(username,phone,password,signature) VALUES("未填写","${phone}","${password}","未填写签名")`);
        if(reslut.affectedRows>0){
            res.json({
                // info: "添加成功",
                status: 1
            });
        }else{
            res.json({
                // info: "添加未成功",
                status: 2
            });
        }
    } catch (err) {
        res.json({
            // info: "添加失败",
            status: 0,
            err
        });
    }
})



router.get("/login",async(req,res)=>{
    let {phone,password}=req.query;
    let str = `SELECT id FROM user WHERE phone="${phone}" AND password="${password}"`;
    let reslut = await query(str);
    if(reslut.length>0){
        // 签发token
        let token = jwt.sign({uname:"hello"},"mysecret",{
            expiresIn:"2h"
        })
        // 返还值
        res.json({
            // info:"登录成功",
            status:1,
            uid:reslut[0].id,
            token
        })
    }else{
        res.json({
            // info:"登录失败",
            status:0,
        })
    }
})




module.exports = router;